<?php

namespace App\Http\Controllers;

use App\Http\Service\Impl\GoodsImpl;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Service;
use GuzzleHttp\Client;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use function foo\func;
use function MongoDB\BSON\toJSON;


/**
 * Class GoodsController
 * @package App\Http\Controllers
 * 商品控制器
 * laravel 让非授权用户不可见 编辑和删除 按钮
 * https://www.jianshu.com/p/ad56ed204323  gate权限的使用
 * https://study.163.com/course/introduction.htm?courseId=1003575006&_trace_c_p_k2_=4c8efd860dad411e858f41f0b5c4b6be
 * composer dumpautoload   执行composer文件
 */
//WithEvents
class GoodsController extends Controller
{
    private $Goodsservice;

    public function __construct()
    {
        $myid = Session::get("mgid");

        $this->Goodsservice = new GoodsImpl();
    }

    /**
     * 客户列表数据--上帝视角
     */
    public function goodslist(Request $request)
    {
        return ["rows" => [], "total" => 100];
        //return $this->Goodsservice->goodslist($request);
    }

    /**
     * 客户跟踪详细信息
     * http://localhost/crm/public/khgzlist
     */
    public function khgzlist(Request $request)
    {
        $client   = new Client();
        $url      = "http://192.168.6.198:8090/u8api/accvouchAdd?server=192.168.1.22&accid=888";
        $response = $client->post($url, ['headers' => ['Content-Type' => 'application/json'], 'json' => $request->toArray()]);
        // 初始化用于构建CASE语句的数组和绑定参数  
        $lshToUpdate = [];
        if ($response->getStatusCode() == 200) {

            //返回成功
            //做BPM更新操作
            $json         = json_decode($response->getBody()->getContents(), true);
            if (isset($json[0])) {
                if ($json[0]['code'] != '1001') {
                    for ($i = 0; $i < count($request->accvouch); $i++) {
                        $detail = $request->accvouch[$i]['detail']; //获取detail数组
                        $lshValues = array_unique(collect($detail)->pluck('lsh')->all());
                        foreach ($lshValues as $lsh) {
                            // 假设每个lsh只对应一个errmsg，如果有多个可能需要进一步处理  
                            $lshToUpdate[$lsh] = $json[$i]['errmsg'];
                        }
                    }
                    $cases = [];
                    $bindings = [];
                    foreach ($lshToUpdate as $lsh => $errmsg) {
                        $cases[] = "WHEN lsh = ? THEN ?";
                        $bindings[] = $lsh;
                        $bindings[] = $errmsg;
                    }
                    $sql = "UPDATE X8060差旅费报销表 SET 凭证编号 = CASE " .
                        implode(' ', $cases) .
                        " END, 凭证创建时间 = ?, 回传信息 = ? WHERE lsh IN (" .
                        implode(',', array_fill(0, count($lshToUpdate), '?')) . ")";
                    // 添加额外的绑定参数  
                    $bindings[] = now();
                    $bindings[] = Session::get('mgid');
                    foreach (array_keys($lshToUpdate) as $lsh) {
                        $bindings[] = $lsh;
                    }
                    //wlog($sql, 1);
                    DB::connection("bpm")->update($sql, $bindings);
                }
            }

            return $json;
        }
    }

    public function goodsjxj(Request $request)
    {

        return ["update" => 'update'];
    }


    /**
     * 客户列表(管理员)
     */
    public function view_goodslist()
    {
        $ssdl = DB::table("ssdl")->get();

        $sszl = DB::table("sszl")->get();

        return view("Goods.goodslist", ["ssdl" => $ssdl, "sszl" => $sszl]);
    }


    /**
     * 个人客户列表
     */
    public function view_recordlist(Request $request)
    {
        $mgid = Session::get("mgid"); //获取用户mgid用于判断是否可以查看别人的领取任务
        $where["mg_id"] = $mgid;
        $info = DB::table("manager")->where($where)->first();
        if ($mgid == '102') {
        }
        return view("Goods.recordlist", ["mgid" => $mgid]);
    }


    /**
     * 编辑礼品详情
     */

    public function view_gooddetail(Request $request)
    {
        $info = DB::table("goodslist")->find($request->id);
        return view("Goods.gooddetail", ["info" => $info]);
    }

    /**
     * 保存更新用户的基础信息
     */
    public function updateCustomInfo(Request $request)
    {
        $where["id"] = $request->id;

        $ups = array(
            "khqm" => $request->khqm,
            "khjc" => $request->khjc,
            "lxr" => $request->lxr,
            "sj" => $request->sj,
            "zj" => $request->zj,
            "shr" => $request->shr,
            "clrq" => $request->clrq,
            "zw" => $request->zw,
            "wx" => $request->wx,
            "qq" => $request->qq,
            "yx" => $request->yx,
            "gzdw" => $request->gzdw,
            "dz" => $request->dz,
            "bz" => $request->bz,
        );
        DB::table("goodslist")->where($where)->update($ups);
        return "success";
    }


    /**
     * 新增礼品
     * 家具软装 全部  沙发  床具  椅子  灯具  桌几  橱柜  陈设饰品
     * 家装空间 全部  客厅  餐厅  卧室  书房  厨房  橱柜  茶室
     */

    public function view_addgood()

    {

        return view("Goods.addgood");
    }


    /**
     * 公海客户列表
     */
    public function view_shoplist()
    {
        return view("Goods.shoplist");
    }

    /**
     * @param Request $request
     * 新增商品
     */

    public function addgood(Request $request)

    {

        $this->Goodsservice->addgood($request);
    }


    /**
     * @param Request $request
     * 门店列表
     */

    public function shoplist(Request $request)

    {


        return $this->Goodsservice->shoplist($request);
    }


    /**
     * @param Request $request
     * 新增门店信息
     */

    public function add_update_shop(Request $request)
    {

        $this->Goodsservice->add_update_shop($request);
    }

    /**
     * 更新用户密码
     */
    public function update_user_password(Request $request)
    {
        $mgid = Session::get("mgid");
        $where["mg_id"] = $mgid;
        $ups["mg_pwd"] = md5($request->xmm);
        DB::table("manager")->where($where)->update($ups);
    }

    /**
     * @param Request $request
     * 删除门店
     */
    public function deleteshop(Request $request)
    {
        $this->Goodsservice->deleteshop($request);
    }

    /**
     * @param Request $request
     * 获取门店详情
     */
    public function detailgood(Request $request)
    {
        $res['data'] = $this->Goodsservice->detailgood($request);
        return json_encode($res);
    }

    /**
     * @param Request $request
     * 兑换记录列表
     */
    public function recordlist(Request $request)
    {

        return $this->Goodsservice->recordlist($request);
    }


    /**
     * @param Request $request
     * 更新物流信息
     */

    public function savewldh(Request $request)

    {

        $this->Goodsservice->savewldh($request);

        return "success";
    }


    /**
     * @param Request $request
     * 作废兑换记录 ---需要记录作废、作废时间-作废部门、并对库存进行增加
     */

    public function dhjlzf(Request $request)

    {

        $this->Goodsservice->dhjlzf($request);
    }


    /**
     * 获取物品类别的子项
     */

    public function getChildren(Request $request)
    {

        return $this->Goodsservice->getChildren($request);
    }

    /**
     * 新增客户--手动新增
     */
    public function addkh(Request $request)
    {
        return $this->Goodsservice->addkh($request);
    }

    /**
     * 客户领取
     */
    public function khlq(Request $request)
    {
        $myid = Session::get("mgid");
        $ups['sflq'] = "是";
        $ids[] = explode(",", $request->ids);
        $where[] = [function ($query) use ($ids) {
            $query->whereIn('id', $ids[0]);
        }];

        $addData = [];
        foreach ($ids[0] as $k => $v) {
            $insert["mid"] = $myid;
            $insert["gid"] = $v;
            $addData[] = $insert;
        }
        //更新客户表的领取状态
        DB::table("goodslist")->where($where)->update($ups);
        Log::info("用户" . $myid . "領取了客戶");
        //批量插入关联中间表
        DB::table("goodlq")->insert($addData);
        Log::info("用户" . $myid . "領取的數據插入了中間表");
        return "success";
    }

    //放弃客户
    public function fqkh(Request $request)
    {
        $myid = Session::get("mgid");
        $ids[] = explode(",", $request->ids);
        $where1[] = [function ($query) use ($ids) {
            $query->whereIn('id', $ids[0]);
        }];
        $ups["sflq"] = '否';
        $where2[] = [function ($query) use ($ids) {
            $query->whereIn('gid', $ids[0]);
        }];
        DB::table("goodslist")->where($where1)->update($ups);
        DB::table("goodlq")->where($where2)->delete();
        Log::info("用户" . $myid . "放棄了客戶");
    }

    /**
     * http://wx.newamstar.com:8078/jiane/public/exportExcel
     */
    public function exportExcel(Request $request)
    {
        ini_set("memory_limit", "800M");
        set_time_limit(0);
        $cellData = [
            ['客户数据一览表'],
            [
                '客户全名', '客户简称', '联系人', '创建时间', '最后联系时间', '跟进人', '性别', '生日', '成立日期', '客户类型', '客户进展', '客户星级', '是否有效', '职位', '微信', 'QQ', '手机', '座机', '邮箱', '工作单位', '地址', '备注', '国家',
                '省',
                '市',
                '城市',
                '区县',
                '行业',
                '传真',
                '来源',
                '报考项目',
                '是否加qq好友',
                '是否解决客户疑虑'
            ],
        ];
        $list = DB::table("goodslist")->where(function ($query) use ($request) {
            if ($request->khqm) {
                $query->where('khqm', 'like', '%' . $request->khqm . '%');
            }
            if ($request->khjc) {
                $query->where('khjc', 'like', '%' . $request->khjc . '%');
            }
            if ($request->zhgjr) {
                $query->where('zhgjr', 'like', '%' . $request->zhgjr . '%');
            }
            if ($request->sfyx) {
                $query->where('sfyx', '%' . $request->sfyx . '%');
            }
        })
            ->select(
                "khqm",
                "khjc",
                "lxr",
                "cjsj",
                "zhlxsj",
                'zhgjr',
                'xb',
                "shr",
                "clrq",
                "khlx",
                "khjz",
                "khxj",
                "sfyx",
                "zw",
                "wx",
                "qq",
                "sj",
                "zj",
                "yx",
                "gzdw",
                "dz",
                "bz",
                "gj",
                "sheng",
                "shi",
                "chs",
                "qx",
                "hy",
                "chz",
                "ly",
                "bkxm",
                "sfjqqhy",
                "sfjjkhyl"
            )
            ->get();

        foreach ($list as $k => $v) {
            $cellData[] = (array)$v;
        }

        Excel::create('客户数据一览表', function ($excel) use ($cellData) {
            $excel->sheet('客户数据一览表', function ($sheet) use ($cellData) {
                $sheet->rows($cellData);
                $sheet->mergeCells('A1:AG1');
                $sheet->cells('A1:AG1', function ($row) {
                    $row->setAlignment('center');
                    $row->setFontWeight('bold');
                    $row->setFontSize('18');
                });
                $sheet->cells('A2:AG2', function ($row) {
                    $row->setAlignment('center');
                    $row->setFontWeight('bold');
                    $row->setFontSize('15');
                });
                $sheet->setWidth(array(
                    'A' => 15,
                    'B' => 15,
                    'C' => 15,
                    'D' => 15,
                    'E' => 15,
                    'F' => 15,
                    'G' => 15,
                    'H' => 15,
                    'I' => 15,
                    'J' => 15,
                    'K' => 15,
                    'L' => 15,
                    'M' => 15,
                    'N' => 15,
                    'O' => 15,
                    'P' => 15,
                    'Q' => 15,
                    'R' => 15,
                    'S' => 15,
                    'T' => 15,
                    'U' => 15,
                    'V' => 15,
                    'W' => 15,
                    'X' => 15,
                    'Y' => 15,
                    'Z' => 15,
                    'AA' => 15,
                    'AB' => 15,
                    'AC' => 15,
                    'AD' => 15,
                    'AE' => 15,
                    'AF' => 15,
                ));
            });
        })->export('csv');
        $myid = Session::get("mgid");
        Log::info("用户" . $myid . "進行了導出操作");
    }


    public function importExcel()
    {

        $filePath = 'storage/' . iconv('UTF-8', 'GBK', 'import') . '.xls';

        Excel::load($filePath, function ($reader) {

            $data = $reader->all()->toArray();

            //批量存储

            $value = [];

            $count = '';

            foreach ($data[0] as $k => $v) {

                $count++;

                //存储表格每行的值

                $value['goodname'] = $v["goodname"];

                $value['price'] = $v["price"];

                $value['score'] = $v["score"];

                DB::table("goodslist")->insert($value);

                //Adver::create($value);

            }

            //返回导入结果

            throw new \Exception("成功导入了" . $count . "条数据");
        });
    }


    /**
     * @param Request $request
     * @return false|string
     * 上传文件
     * 业务逻辑在helpers中,传入$request即可
     */

    public function uploadfile(Request $request)
    {
        $res["msg"] = date('Ymd', time()) . '/' . uploadfile($request);
        return json_encode($res);
    }


    public function senddata()
    {
        $list = DB::select("select * from zhyl_sys_goodslist");
        //dd($list);
        //return view("Goods.senddata");

    }
}
